#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "double_linkedlist.h"

// 数据结构定义
typedef struct Person {
    char name[50];
    int age;
} Person;

// 打印函数，用于遍历链表时打印数据
void print_person(const void *data) {
    const Person *person = (const Person *)data;
    printf("姓名: %s, 年龄: %d\n", person->name, person->age);
}

int main()
{
    dlisthead_t *list = NULL;
    int ret;

    // 初始化链表
    ret = dlisthead_init(&list, sizeof(Person));
    if (ret != 0) {
        printf("初始化链表失败\n");
        return -1;
    }

    // 插入数据：头插法
    Person p1 = {"Alice", 30};
    ret = dlist_insert(list, &p1);
    if (ret != 0) {
        printf("插入 Alice 失败\n");
    }

    Person p2 = {"Bob", 25};
    ret = dlist_insert(list, &p2);
    if (ret != 0) {
        printf("插入 Bob 失败\n");
    }

    Person p3 = {"Charlie", 35};
    ret = dlist_insert_tail(list, &p3);
    if (ret != 0) {
        printf("插入 Charlie 失败\n");
    }

    Person p4 = {"David", 40};
    ret = dlist_insert_tail(list, &p4);
    if (ret != 0) {
        printf("插入 David 失败\n");
    }

    Person p5 = {"Tom", 40};
    ret = dlist_insert_tail(list, &p5);
    if (ret != 0) {
        printf("插入 Tom 失败\n");
    }


    // 遍历链表并打印
    printf("遍历链表:\n");
    dlist_traval(list, print_person);

    // 查找中心节点
    Person *center = (Person *)find_center_node(list);
    if (center) {
        printf("中心节点是: 姓名: %s, 年龄: %d\n", center->name, center->age);
    } else {
        printf("未找到中心节点\n");
    }

    Person p6 = {"Timi", 41};
    ret = dlist_insert_tail(list, &p6);
    if (ret != 0) {
        printf("插入 Timi 失败\n");
    } else {
        printf("插入 Timi 成功\n"); 
    }

    Person p7 = {"Mike", 47};
    ret = dlist_insert_tail(list, &p7);
    if (ret != 0) {
        printf("插入 Mike 失败\n");
    } else {
        printf("插入 Mike 成功\n");
    }

    // 反转链表
    reverse_list(list);
    printf("链表反转后的结果:\n");
    dlist_traval(list, print_person);

    // 再次查找中心节点
    center = (Person *)find_center_node(list);
    if (center) {
        printf("反转后的中心节点是: 姓名: %s, 年龄: %d\n", center->name, center->age);
    } else {
        printf("未找到反转后的中心节点\n");
    }

    // 销毁链表
    dlist_destroy(&list);
    printf("链表已销毁\n");

    return 0;
}


